package com.scott.mysocket;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class UploadPicServer {

	public static void main(String[] args) throws IOException {
		System.out.println("上传图片服务器端开启......");
		//服务器端对象
		ServerSocket ss = new ServerSocket(10006);
		
		Socket s = ss.accept();
		String ip = s.getInetAddress().getHostAddress();
		System.out.println(ip + "......connected");
		
		File file = getFile("C:/Users/Scott/Desktop/", ip);
		
		InputStream in = s.getInputStream();
		FileOutputStream fos = new FileOutputStream(file);
			
		byte[] buf = new byte[1024];
		int len = 0;
		while ((len = in.read(buf)) != -1) {
			fos.write(buf, 0, len);
		}
			
		//回馈客户端数据
		OutputStream out = s.getOutputStream();
		out.write("图片上传成功".getBytes());
			
		fos.close();
		s.close();
		ss.close();
	}

	private static File getFile(String dir, String ip) {
		File pic_dir = new File(dir);
		if (!pic_dir.exists()) {
			pic_dir.mkdirs();
		}
		int count = 1;
		File file = new File(pic_dir, ip + "(" + count + ").jpg");
		while (file.exists()) {
			count++;
			file = new File(pic_dir, ip + "(" + count + ").jpg");
		}
		return file;
	}

}
